﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Diagnostics;
using CAUNetLogin.Util.SystemLib;
using System.Reflection;
using System.Runtime.InteropServices;

namespace CAUNetLogin
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Guid ownGUID = new Guid(((GuidAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(GuidAttribute))).Value);
            Guid proGUID;
            int ownPID = Process.GetCurrentProcess().Id;
            int proPID;
            bool isInstanceExist = false;

            foreach (Process p in Process.GetProcesses())
            {
                try
                {
                    proGUID = new Guid(((GuidAttribute)Attribute.GetCustomAttribute(Assembly.LoadFile(p.MainModule.FileName), typeof(GuidAttribute))).Value);
                    proPID = p.Id;
                    if (proGUID.Equals(ownGUID) && proPID != ownPID)
                    {
                        MessageBox.Show("程序已运行,请查看系统托盘","提示");
                        SystemWindow.ShowWindowAsync(p.MainWindowHandle, 1);
                        SystemWindow.SetForegroundWindow(p.MainWindowHandle);
                        isInstanceExist = true;

                        //Environment.Exit(Environment.ExitCode);
                    }
                }
                catch
                {
                    continue;//遇上进程访问异常就跳过该进程
                }
            }

            //若未被Exit，正常启动
            if (!isInstanceExist)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new CAULogin());
            }
        }
    }
}
